package com.thinta.wind.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider


/*********************************************************
 * 版权信息：2021/5/10 14:17北京振中电子技术有限公司版权所有<p>
 * 创建作者：Wind<p>
 * 创建日期：2021/5/10 14:17<p>
 * *******************************************************<p>
 * 更新历史：    作者      日期      更新摘要<p>
 * <p>
 * *******************************************************<p>
 * 类功能说明：<p>
 */
abstract class BaseFragment<VM : BaseModel?, V : ViewDataBinding?> : Fragment(){

    var mContext : Context? = null

    var dataBinding : V? = null

    var viewModel : VM? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        mContext = inflater.context
        dataBinding?.lifecycleOwner = this
        viewModel = ViewModelProvider(this, getModelFactory()).get(viewModelClass())
        return dataBinding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        afterCreate()
    }

    abstract fun getModelFactory() : ViewModelProvider.NewInstanceFactory

    abstract fun viewModelClass(): Class<VM>//获取 ViewModel 类

    @LayoutRes
    protected abstract fun getLayoutId(): Int

    protected abstract fun afterCreate()

    protected fun initViewBinding(itemView : View) : ViewDataBinding? =
        if (null == DataBindingUtil.getBinding(itemView)) {
            DataBindingUtil.bind(itemView)
        } else {
            DataBindingUtil.getBinding(itemView)
        }
}